<?php

class CallbackController extends Zend_Controller_Action
{

    public function init()
    {
        $this->req = $this->getRequest();

    }
    /*授权回调获取用户信息*/
    public function indexAction()
    {
        /*获取code兑换access_token*/
        if (isset($_GET['code'])) {
            $code = $_GET['code'];
            $weixin_appid = \Util\Config::get('weixin_appid','Environment');
            $weixin_appsecret = \Util\Config::get('weixin_appsecret','Environment');
            $get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$weixin_appid&secret=$weixin_appsecret&code=$code&grant_type=authorization_code";
            $token_url = $this->http_get($get_token_url);
            $token_url = json_decode($token_url,true);

            $refresh_token = $token_url["refresh_token"];
            $access_token = $token_url["access_token"];
            $open_id = $token_url["openid"];
            $info = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$open_id&lang=zh_CN";
            $user_info = $this->http_get($info);
            $user_info = json_decode($user_info,true);
            if ($user_info) {
                $article = new \Base\Rest();
                $post_data = array(
                    'openid'=>$user_info['openid'],
                    'nickname'=>$user_info['nickname'],
                    'headimgurl'=>$user_info['headimgurl']
                );
                $req= array();
                $post = array('payload'=>base64_encode(http_build_query($post_data)));
                $rest_res = $article->post('User',$req,$post);
                if ($rest_res->isSuccess() == true) {
                    if (isset($_GET['state'])) {
                        $this->_redirect($_GET['state']);
                    } else {
                        $this->_redirect('/my/index');
                    }
                } else {
                    exit('服务器内部错误');
                }
            }else{
                exit('获取用户信息失败哦');
            }
        }else{
            echo 'code null';
        }
    }
    //HTTP请求（支持HTTP/HTTPS，支持GET/POST）
    public function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

}



